<template>
  <div class="plan-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>生产计划</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入计划编号/名称"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.sourceType"
            placeholder="请选择订单来源"
            clearable
            class="w-180"
          >
            <el-option label="销售订单" :value="1" />
            <el-option label="库存备货" :value="2" />
            <el-option label="其他" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.productName"
            placeholder="请选择成品名称"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="onProductRemoteSearch"
            :loading="productLoading"
            class="w-220"
            @visible-change="onProductDropdownVisible"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="`${item.productname}（${item.productcard}）`"
              :value="item.productname"
            >
              <div class="option-item">
                <div class="option-title">{{ item.productname }}</div>
                <div class="option-desc">
                  <span>{{ item.productcard }}</span>
                  <el-divider direction="vertical" />
                  <span>{{ item.productmodelsame }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="未分解" :value="1" />
            <el-option label="已分解" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已关闭" :value="4" />
            <el-option label="已撤回" :value="5" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button @click="handleEditSelected">编辑</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">删除</el-button>
      </div>

      <el-table
        :data="rows"
        border
        stripe
        :loading="loading"
        class="plan-table"
        height="640"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="planCode" label="计划编号" min-width="140" />
        <el-table-column prop="planName" label="计划名称" min-width="160" />
        <el-table-column prop="workOrderCount" label="工单数量" width="120" align="center" />
        <el-table-column label="来源类型" width="140">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.sourceTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="成品名称" min-width="160" />
        <el-table-column prop="productId" label="成品编号" min-width="160" />
        <el-table-column prop="productmodelsame" label="规格型号" min-width="140" />
        <el-table-column prop="productunit" label="单位" width="80" align="center" />
        <el-table-column prop="planCount" label="计划数量" width="120" align="center" />
        <el-table-column label="计划开工时间" min-width="150">
          <template #default="scope">{{ formatDate(scope.row.planStartTime) }}</template>
        </el-table-column>
        <el-table-column label="计划完工时间" min-width="150">
          <template #default="scope">{{ formatDate(scope.row.planEndTime) }}</template>
        </el-table-column>
        <el-table-column label="需求日期" min-width="140">
          <template #default="scope">{{ formatDate(scope.row.demandDate) }}</template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              link
              @click="handleSplit(scope.row)"
            >
              分解
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              type="warning"
              link
              @click="handleRecall(scope.row)"
            >
              撤回
            </el-button>
            <el-divider v-if="scope.row.status === 1 || scope.row.status === 2" direction="vertical" />
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ArrowRight, HomeFilled, Menu, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'
import { useRouter } from 'vue-router'

interface ProductionPlanItem {
  id: number
  planCode: string
  planName: string
  workOrderCount: number
  sourceType: number
  sourceTypeName: string
  productId: string
  productName: string
  productmodelsame: string
  productunit: string
  planCount: number
  planStartTime: string
  planEndTime: string
  demandDate: string
  status: number
  statusName: string
}

interface ProductOption {
  id: number
  productcard: string
  productname: string
  productmodelsame: string
  productunit: string
}

// 生产工单列表项接口（用于本地存储）
interface ProductionOrderItem {
  id: number
  orderCode: string
  orderName: string
  planName: string
  productName: string
  productCode: string
  specModel: string
  productType: string
  unit: string
  demandDate: string
  planQuantity: number
  actualQuantity: number
  planStartTime: string
  planFinishTime: string
  actualStartTime: string
  actualFinishTime: string
  status: string
  progress: {
    prepare: number
    execute: number
    quality: number
    done: number
  }
}

// BOM相关接口
interface BomDTO {
  id: number
  bomcode: string
  bomname: string
  productid: number
  productcode: string
  productname: string
  version: string
  bomstate: boolean
  bomdes: string
}

interface BomDetailDTO {
  id: number
  bomid: number
  materialid: number
  materialcode: string
  materialname: string
  specification: string
  unit: string
  quantity: number
  lossrate: number
  sortorder: number
  remark: string
  nodetype: number
  nodekey: string
  parentnodekey: string
}

// 生产工单接口
interface WorkOrderCreateDTO {
  orderCode?: string
  orderName: string
  planId: number
  planName: string
  productName: string
  productCode: string
  specModel: string
  productType: string
  unit: string
  demandDate: string
  planQuantity: number
  planStartTime: string
  planFinishTime: string
  status: string
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number
  msg: string
  data: T[]
  totalCount: number
  pageCount: number
}
const router = useRouter()
interface ApiResultResponse<T> {
  code: number
  msg: string
  data: T
}

const loading = ref(false)
const rows = ref<ProductionPlanItem[]>([])
const pager = reactive({ page: 1, size: 10, total: 0 })
const searchForm = reactive({
  keyword: '',
  sourceType: undefined as number | undefined,
  productName: '',
  status: undefined as number | undefined
})

const multipleSelection = ref<ProductionPlanItem[]>([])
const productOptions = ref<ProductOption[]>([])
const productLoading = ref(false)

const fetchList = async () => {
  loading.value = true
  try {
    const statusFilter =
      typeof searchForm.status === 'number' && searchForm.status > 0 && searchForm.status <= 3
        ? searchForm.status
        : 0
    const response = await https.Reads.get('/AProduction_Plan/GetPlanPage', {
      params: {
        keyword: searchForm.keyword || undefined,
        sourceType: searchForm.sourceType ?? 0,
        productName: searchForm.productName || undefined,
        status: statusFilter,
        pageIndex: pager.page,
        pageSize: pager.size
      }
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取生产计划失败'))
    }
    rows.value = payload?.data ?? payload?.Data ?? []
    pager.total = payload?.totalCount ?? payload?.TotalCount ?? rows.value.length
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取生产计划失败'))
  } finally {
    loading.value = false
  }
}

const fetchProductOptions = async (keyword = '') => {
  productLoading.value = true
  try {
    const response = await https.Reads.get('/AProduction_Plan/GetPlanProducts', { params: { keyword } })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取产品列表失败'))
    }
    productOptions.value = payload?.data ?? payload?.Data ?? []
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取产品列表失败'))
  } finally {
    productLoading.value = false
  }
}

const onProductRemoteSearch = (value: string) => {
  fetchProductOptions(value)
}

const onProductDropdownVisible = (visible: boolean) => {
  if (visible && !productOptions.value.length) {
    fetchProductOptions()
  }
}

const handleSearch = () => {
  pager.page = 1
  fetchList()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.sourceType = undefined
  searchForm.productName = ''
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

const onSelectionChange = (selection: ProductionPlanItem[]) => {
  multipleSelection.value = selection
}

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  fetchList()
}

const onPageChange = (page: number) => {
  pager.page = page
  fetchList()
}

const handleAdd = () => {
  router.push({ path: '/AProduction_PlanAdd' })
}

const handleEditSelected = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请先选择要编辑的生产计划')
    return
  }
  handleEdit(multipleSelection.value[0]!)
}

const handleEdit = (row: ProductionPlanItem) => {
  router.push({ path: '/AProduction_PlanAdd', query: { id: row.id } })
}

const handleBatchDelete = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择要删除的生产计划')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${multipleSelection.value.length} 条生产计划吗？`, '提示', {
      type: 'warning'
    })
    const ids = multipleSelection.value.map(item => item.id)
    const response = await https.Writes.post('/Aproduction_planB/Delete', { ids })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload)) {
      throw new Error(getResponseMessage(payload, '删除失败'))
    }
    ElMessage.success(getResponseMessage(payload, '删除成功'))
    multipleSelection.value = []
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(getErrorMessage(error, '删除失败'))
    }
  }
}

// 根据产品名称查找BOM
const findBomByProductName = async (productName: string): Promise<BomDTO | null> => {
  try {
    const response = await https.Reads.get<ApiPageingResponse<BomDTO>>('/Bom/BomGetList', {
      params: {
        productname: productName,
        bomstate: true, // 只查找启用的BOM
        pageindex: 1,
        pagesize: 100
      }
    })
    const payload = extractPayload(response)
    if (isRequestSuccess(payload) && Array.isArray(payload?.data ?? payload?.Data)) {
      const bomList = payload?.data ?? payload?.Data ?? []
      // 精确匹配产品名称
      const bom = bomList.find((item: { productname: string; bomstate: any }) => item.productname === productName && item.bomstate)
      return bom || null
    }
  } catch (error) {
    console.error('查找BOM失败:', error)
  }
  return null
}

// 获取BOM明细列表
const fetchBomDetails = async (bomId: number): Promise<BomDetailDTO[]> => {
  try {
    const response = await https.Reads.get<ApiPageingResponse<BomDetailDTO>>('/Bom/BomGetDetailList', {
      params: {
        bomid: bomId,
        pageindex: 1,
        pagesize: 1000 // 获取所有明细
      }
    })
    const payload = extractPayload(response)
    if (isRequestSuccess(payload) && Array.isArray(payload?.data ?? payload?.Data)) {
      return payload?.data ?? payload?.Data ?? []
    }
  } catch (error) {
    console.error('获取BOM明细失败:', error)
  }
  return []
}

// 生成工单编号（可以根据实际业务规则调整）
const generateOrderCode = (planCode: string, index: number): string => {
  const timestamp = new Date().getTime().toString().slice(-6)
  return `${planCode}-${String(index + 1).padStart(3, '0')}-${timestamp}`
}

// 判断是否为根节点（二级节点）
const isRootNode = (parentNodeKey: string | undefined | null): boolean => {
  if (!parentNodeKey) return true
  const key = parentNodeKey.trim().toUpperCase()
  return key === 'ROOT' || key === ''
}

// 递归获取BOM的所有明细（包括子产品和子物料，都要生成工单）
const getAllWorkOrderItems = async (
  bomDetails: BomDetailDTO[],
  planCount: number,
  parentQuantity: number = 1,
  isRootLevel: boolean = true
): Promise<Array<BomDetailDTO & { calculatedQuantity: number; isProduct: boolean }>> => {
  const allItems: Array<BomDetailDTO & { calculatedQuantity: number; isProduct: boolean }> = []

  // 如果是根级别，只处理二级节点（parentnodekey为ROOT的节点）
  // 如果不是根级别，处理所有节点
  const detailsToProcess = isRootLevel
    ? bomDetails.filter(detail => isRootNode(detail.parentnodekey))
    : bomDetails

  for (const detail of detailsToProcess) {
    const baseQuantity = detail.quantity || 1
    const lossRate = detail.lossrate || 0
    // 计算实际需要的数量：计划数量 * 父级数量 * 使用量 * (1 + 损耗率)
    const calculatedQuantity = Math.ceil(
      planCount * parentQuantity * baseQuantity * (1 + lossRate / 100)
    )

    // 判断节点类型：nodetype=1表示产品，nodetype=2或0或undefined表示物料
    const isProduct = detail.nodetype === 1

    // 无论是产品还是物料，都先添加到结果中（需要生成工单）
    allItems.push({
      ...detail,
      calculatedQuantity,
      isProduct
    })

    // 如果是产品类型（nodetype=1），需要递归处理其子BOM
    if (isProduct) {
      // 查找该产品对应的BOM
      const productBom = await findBomByProductName(detail.materialname)
      if (productBom) {
        // 获取该产品BOM的明细
        const productBomDetails = await fetchBomDetails(productBom.id)
        if (productBomDetails && productBomDetails.length > 0) {
          // 递归处理子BOM的所有明细（包括子产品和子物料）
          const subItems = await getAllWorkOrderItems(
            productBomDetails,
            planCount,
            baseQuantity * (1 + lossRate / 100),
            false // 子BOM处理所有明细
          )
          allItems.push(...subItems)
        }
      }
      // 如果找不到子BOM，该产品仍然会生成工单（已在上面添加）
    }
  }

  return allItems
}

// 根据BOM明细生成生产工单数据（包括子产品和子物料）
const generateWorkOrders = async (
  plan: ProductionPlanItem,
  bomDetails: BomDetailDTO[]
): Promise<WorkOrderCreateDTO[]> => {
  if (!bomDetails || bomDetails.length === 0) {
    return []
  }

  // 获取所有明细（包括产品和物料，递归处理子BOM）
  const allItems = await getAllWorkOrderItems(bomDetails, plan.planCount)

  if (allItems.length === 0) {
    return []
  }

  // 按物料/产品编号和名称分组，合并相同物料/产品的工单
  const itemMap = new Map<string, WorkOrderCreateDTO>()

  for (const item of allItems) {
    // 使用编号和名称作为唯一键
    const key = `${item.materialcode}-${item.materialname}`
    
    if (itemMap.has(key)) {
      // 如果已存在相同物料/产品，累加数量
      const existing = itemMap.get(key)!
      existing.planQuantity += item.calculatedQuantity
    } else {
      // 创建新的工单
      // 根据isProduct标识判断是产品还是物料
      // nodetype=1表示产品（半成品），nodetype=2或0表示物料
      const productType = item.isProduct ? '半成品' : '物料'
      
      itemMap.set(key, {
        orderName: `${plan.planName}-${item.materialname}${item.isProduct ? '(产品)' : '(物料)'}`,
        planId: plan.id,
        planName: plan.planName,
        productName: item.materialname,
        productCode: item.materialcode,
        specModel: item.specification || '',
        productType: productType,
        unit: item.unit || plan.productunit,
        demandDate: plan.demandDate,
        planQuantity: item.calculatedQuantity,
        planStartTime: plan.planStartTime,
        planFinishTime: plan.planEndTime,
        status: '待排产'
      })
    }
  }

  return Array.from(itemMap.values())
}

// 将工单数据转换为生产工单列表格式
const convertToProductionOrderItem = (
  order: WorkOrderCreateDTO,
  index: number
): ProductionOrderItem => {
  return {
    id: Date.now() + index,
    orderCode: order.orderCode || generateOrderCode(order.planName, index),
    orderName: order.orderName,
    planName: order.planName,
    productName: order.productName,
    productCode: order.productCode,
    specModel: order.specModel,
    productType: order.productType,
    unit: order.unit,
    demandDate: order.demandDate,
    planQuantity: order.planQuantity,
    actualQuantity: 0,
    planStartTime: order.planStartTime,
    planFinishTime: order.planFinishTime,
    actualStartTime: '',
    actualFinishTime: '',
    status: order.status || '待排产',
    progress: {
      prepare: 0,
      execute: 0,
      quality: 0,
      done: 0
    }
  }
}

// 保存工单到本地存储（供生产工单视图使用）
const saveWorkOrdersToLocalStorage = (orders: ProductionOrderItem[]) => {
  try {
    const existing = localStorage.getItem('production_work_orders')
    let allOrders: ProductionOrderItem[] = []
    
    if (existing) {
      try {
        allOrders = JSON.parse(existing)
      } catch (e) {
        console.warn('解析本地存储的工单数据失败:', e)
      }
    }
    
    // 合并新工单（避免重复）
    const existingCodes = new Set(allOrders.map(o => o.orderCode))
    const newOrders = orders.filter(o => !existingCodes.has(o.orderCode))
    allOrders = [...newOrders, ...allOrders]
    
    localStorage.setItem('production_work_orders', JSON.stringify(allOrders))
    
    // 触发自定义事件，通知生产工单视图更新
    window.dispatchEvent(new CustomEvent('workOrdersUpdated', { detail: newOrders }))
    
    return true
  } catch (error) {
    console.error('保存工单到本地存储失败:', error)
    return false
  }
}

// 创建生产工单（调用后端API，如果失败则保存到本地）
const createWorkOrders = async (workOrders: WorkOrderCreateDTO[]): Promise<{
  success: boolean
  createdOrders: ProductionOrderItem[]
  apiSuccessCount: number
}> => {
  const createdOrders: ProductionOrderItem[] = []
  let apiSuccessCount = 0
  
  try {
    // 如果后端有批量创建接口，可以使用批量接口
    // 这里先尝试单个创建，如果后端有批量接口可以优化
    const createPromises = workOrders.map(async (order, index) => {
      // 生成工单编号
      order.orderCode = generateOrderCode(workOrders[0]?.planName || 'PLAN', index)
      
      // 转换为生产工单格式
      const orderItem = convertToProductionOrderItem(order, index)
      createdOrders.push(orderItem)
      
      // 调用后端API创建工单
      try {
        const response = await https.Writes.post<ApiResultResponse<any>>(
          '/AProduction_Work_Order/CreateWorkOrder',
          order
        )
        const payload = extractPayload(response)
        if (isRequestSuccess(payload)) {
          // API创建成功，更新ID（如果后端返回了ID）
          if (payload?.data?.id) {
            orderItem.id = payload.data.id
          }
          apiSuccessCount++
          return true
        } else {
          console.warn('创建工单失败:', getResponseMessage(payload, '未知错误'))
          return false
        }
      } catch (error: any) {
        // 如果接口不存在或调用失败，继续处理但不标记为API成功
        if (error.response?.status === 404) {
          console.info('创建工单接口不存在，将保存到本地存储')
        } else {
          console.warn('创建工单API调用失败:', error)
        }
        return false
      }
    })

    await Promise.all(createPromises)
    
    // 无论API是否成功，都保存到本地存储（确保数据不丢失）
    saveWorkOrdersToLocalStorage(createdOrders)
    
    return {
      success: createdOrders.length > 0,
      createdOrders,
      apiSuccessCount
    }
  } catch (error) {
    console.error('创建生产工单失败:', error)
    // 即使出错，也保存到本地存储
    if (createdOrders.length > 0) {
      saveWorkOrdersToLocalStorage(createdOrders)
    }
    return {
      success: createdOrders.length > 0,
      createdOrders,
      apiSuccessCount
    }
  }
}

// 处理分解功能
const handleSplit = async (row: ProductionPlanItem) => {
  // 检查计划状态
  if (row.status === 2) {
    ElMessage.warning('该计划已经分解，无需重复分解')
    return
  }

  try {
    // 确认分解操作
    await ElMessageBox.confirm(
      `确定要分解生产计划"${row.planName}"吗？\n系统将根据BOM自动生成生产工单。`,
      '确认分解',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    ElMessage.info('正在查找BOM信息...')

    // 1. 根据产品名称查找BOM
    const bom = await findBomByProductName(row.productName)
    if (!bom) {
      ElMessage.error(`未找到产品"${row.productName}"对应的BOM信息，无法分解`)
      return
    }

    ElMessage.info('正在获取BOM明细...')

    // 2. 获取BOM明细列表
    const bomDetails = await fetchBomDetails(bom.id)
    if (!bomDetails || bomDetails.length === 0) {
      ElMessage.warning(`BOM"${bom.bomname}"没有明细信息，无法生成工单`)
      return
    }

    ElMessage.info(`找到${bomDetails.length}条BOM明细，正在生成生产工单...`)

    // 3. 根据BOM明细生成生产工单数据（递归处理子BOM）
    const workOrders = await generateWorkOrders(row, bomDetails)
    if (workOrders.length === 0) {
      ElMessage.warning('未能生成有效的生产工单数据')
      return
    }

    // 4. 显示生成的工单预览（可选）
    const previewMessage = `将生成 ${workOrders.length} 个生产工单：\n${workOrders
      .slice(0, 5)
      .map((o, i) => `${i + 1}. ${o.orderName} (${o.productName})`)
      .join('\n')}${workOrders.length > 5 ? `\n... 还有 ${workOrders.length - 5} 个工单` : ''}`

    await ElMessageBox.confirm(previewMessage, '确认创建工单', {
      confirmButtonText: '确认创建',
      cancelButtonText: '取消',
      type: 'info',
      dangerouslyUseHTMLString: false
    })

    // 5. 创建生产工单
    ElMessage.info('正在创建生产工单...')
    const result = await createWorkOrders(workOrders)

    if (result.success) {
      if (result.apiSuccessCount > 0) {
        ElMessage.success(
          `成功分解生产计划！已通过API创建 ${result.apiSuccessCount} 个生产工单，共生成 ${result.createdOrders.length} 个工单`
        )
      } else {
        ElMessage.success(
          `成功分解生产计划！已生成 ${result.createdOrders.length} 个生产工单（已保存到本地，后端接口待实现）`
        )
      }
      
      // 刷新列表
      await fetchList()
      
      // 提示用户可以查看生产工单
      ElMessage.info({
        message: `工单已添加到生产工单列表，您可以前往"生产工单"页面查看`,
        duration: 3000
      })
    } else {
      ElMessage.error('创建生产工单失败，请稍后重试')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      // 用户取消操作
      return
    }
    console.error('分解生产计划失败:', error)
    ElMessage.error(getErrorMessage(error, '分解生产计划失败，请稍后重试'))
  }
}

const handleRecall = async (row: ProductionPlanItem) => {
  if (row.status !== 2) {
    ElMessage.warning('只能撤回已分解的计划')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要撤回生产计划"${row.planName}"吗？`, '确认撤回', {
      type: 'warning'
    })
    const response = await https.Writes.post('/Aproduction_planB/Recall', { id: row.id })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload)) {
      throw new Error(getResponseMessage(payload, '撤回失败'))
    }
    ElMessage.success(getResponseMessage(payload, '撤回成功'))
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(getErrorMessage(error, '撤回失败'))
    }
  }
}

const formatDate = (value?: string | Date) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return '-'
  }
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const statusTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'warning'
    case 2:
      return 'info'
    case 3:
      return 'success'
    case 4:
      return 'danger'
    case 5:
      return 'default'
    default:
      return 'info'
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.plan-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.plan-table {
  width: 100%;
}

.mt-12 {
  margin-top: 12px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}

.w-180 {
  width: 180px;
}

.w-220 {
  width: 220px;
}

.option-item {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.option-title {
  font-weight: 600;
}

.option-desc {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>


